<template>
  <el-dialog :title="title"
             :visible="value"
             :width="dialogWidth"
             class="dialog-box"
             :before-close="handleClose"
             :close-on-click-modal="false"
             @input="$emit('input', $event)">
    <template>
      <span v-if="!stopLoop"
            class="warning-item">
        <img class="execute-gif"
             :src="executeGif">
        {{ progressContent }}
      </span>
      <span v-if="stopLoop"
            class="warning-item">
        <img class="warning-img"
             :src="warning">
        {{ tipContent }}
      </span>
    </template>
    <div v-if="stopLoop"
         slot="footer"
         class="dialog-footer">
      <el-button @click="handleCancel">我知道了</el-button>
    </div>
  </el-dialog>
</template>
<script>
import executeGif from '@/static/images/execute.gif'
import warning from '@/static/images/warning.png'
import axios from 'axios';

function regexId (url) {
  const regex = /{([^}]+)}/;
  const [_, key] = url.match(regex) || [];
  if (!key) {
    console.log("未找到匹配的ID");
  }
  return key;
}

export default {
  name: "TableBatchSet",
  components: {
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      // visible: false,
      stopLoop: false,
      timer: null,
      // taskId: null,
      result: {},
      idCountExceeded: null,
      component: {},
      executeGif,
      warning
    }
  },
  computed: {
    title () {
      return this.component?.title || "提示";
    },
    dialogWidth () {
      return this.component?.width || "420px";
    },
    progressContent () {
      const { totalNum, finishedNum, unfinishedNum } = this.result
      return `导入订单共${totalNum || this.idCountExceeded}单，已处理${finishedNum || 0}单，剩余${unfinishedNum || this.idCountExceeded}单`
    },
    tipContent () {
      return `正在进行批量导入操作，离开页面后，批量操作结果可点击导航栏-任务中心图标查看。`
    },
    taskUrl () {
      return this.data?.taskUrl
    },
    taskId () {
      return this.data?.id
    }
  },
  watch: {
    value () {
      this.stopLoop = false
      this.result = {}
      this.idCountExceeded = this.data.count
      this.procedure(this.taskUrl, this.taskId)
      // this.taskId = null
    }
  },
  mounted () {
    // Dialog.register(this)
  },
  beforeDestroy () {
    this.$once("hook:beforeDestroy", () => clearInterval(this.timer));
  },
  methods: {
    handleClose () {
      if (this.stopLoop) {
        this.timer = setTimeout(() => {
          this.stopLoop = true
        }, 0);
        // this.value = false;
        this.$emit('input', false)
        this.$emit("refresh");
        return;
      }
      this.stopLoop = true;
      // this.visible = false;
    },
    handleCancel () {
      this.timer = setTimeout(() => {
        this.stopLoop = true
      }, 0);
      // this.visible = false
      this.$emit('input', false)
      this.$emit("refresh");
    },
    async loopUntilProgressIsOne (taskUrl, id) {
      let result;
      const interval = 3000; // 调用接口的时间间隔，单位为毫秒
      do {
        try {
          result = await this.fetchBatchId(taskUrl, id);
          await new Promise(resolve => setTimeout(resolve, interval)); // 等待一段时间后再继续调用接口
          this.$set(this, 'result', result);
        } catch (error) {
          console.error('批量任务进程异常' + error);
          break;
        }
      } while (result.progress !== 1 && !this.stopLoop);

      return result;
    },

    async fetchBatchId (taskUrl, id) {
      const key = regexId(taskUrl);
      const apiUrl = taskUrl.replace(`{${key}}`, id);
      try {
        const response = await axios.get(apiUrl);
        return response.data;
      } catch (error) {
        console.error(error);
        throw error;
      }
    },
    async procedure (taskUrl, id) {
      // this.loading = true
      const response = await this.loopUntilProgressIsOne(taskUrl, id)
      this.result = response
      if (this.result.progress === 1) {
        // this.visible = false;
        this.$emit('input', false)
        // this.$message({ type: "success", message: "操作成功" });
        this.$emit("refresh");
      }
    }
  },
}
</script>

<style scoped>
.dialog-box {
  font-size: 16px;
  display: flex;
  align-items: center;
}

.dialog-box >>> .el-dialog__header {
  padding: 10px 15px 10px;
  background: #ffffff;
}
.dialog-box >>> .el-dialog__headerbtn {
  top: 14px;
}
.dialog-box {
  text-align: left;
}

.dialog-box >>> .el-dialog__body {
  padding: 10px 15px;
  /* font-size: 16pc; */
}
.dialog-box >>> .el-dialog__footer {
  padding: 5px 15px 15px;
}

.loading-box {
  width: 20px;
  height: 20px;
}
/* .loading-box >>> .el-loading-spinner .circular {
  width: 20px !important;
  height: 20px !important;
} */
.loading-box >>> .el-loading-spinner {
  top: 100% !important;
  /* margin-right: 5px; */
}
.loading-txt {
  padding-left: 5px;
}
.warning-item {
  line-height: 20px;
  display: flex;
  align-items: center;
}
.warning-item .warning-img {
  width: 48px;
  height: 48px;
  /* font-size: 50px; */
  color: #e6a23c;
  padding-right: 20px;
}
.execute-gif {
  width: 48px;
  height: 48px;
  padding-right: 15px;
}
.dialog-footer {
  text-align: right;
}
</style>